package com.heima.article.service.Impl;


import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleFreemarkerService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import javassist.bytecode.ByteArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class ApArticleFreemarkerServiceImpl implements ApArticleFreemarkerService {

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Async
    @Override
    public void buildArticleToMinIO(ApArticle apArticle, String content){
        // 1 参数检验
        if(content == null || apArticle==null){
            return;
        }

        // 2 找寻到对应的Freemarker
        StringWriter sw = new StringWriter();
        Template template = null;
        try {
            template = configuration.getTemplate("article.ftl");
            Map<String, Object> data = new HashMap<>();
            data.put("content", JSONArray.parseArray(content));
            template.process(data,sw); // 成功获取界面
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 保存到minio中
        ByteArrayInputStream fis = new ByteArrayInputStream(sw.toString().getBytes());
        String path = fileStorageService.uploadHtmlFile("", apArticle.getId() + ".html", fis);

        // 修改ap_article表,保存static_url字段
        apArticle.setStaticUrl(path);
        apArticleMapper.updateById(apArticle);


    }


}
